<template>
  <div>
    <BasicTable @register="registerTable" @fetch-success="onFetchSuccess" ref="tableRef">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate" v-if="hasPermission(['system:role:create'])">
          新增
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
              ifShow: hasPermission(['system:role:update']),
            },
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              color: 'error',
              ifShow: hasPermission(['system:role:delete']),
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
          :dropDownActions="[
            {
              label: '菜单权限',
              icon: 'ph:key-bold',
              onClick: handlePower.bind(null, record),
              ifShow: hasPermission(['system:permission:assign-role-menu']),
            },
            {
              label: '数据权限',
              icon: 'ph:key-bold',
              onClick: handleDataPermissions.bind(null, record),
              ifShow: hasPermission(['system:permission:assign-role-data-scope']),
            },
          ]"
        />
      </template>
    </BasicTable>
    <Drawer @register="registerDrawer" @success="handleSuccess" :type="type" />
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, unref, ref } from 'vue';
import { BasicTable, useTable, TableAction, TableActionType } from '/@/components/Table';
import {
  roleList,
  addRole,
  editRole,
  deleteRole,
  assignRole,
  roleDataAssign,
} from '/@/api/backs/system/role';
import { message } from 'ant-design-vue';
import { useDrawer } from '/@/components/Drawer';
import Drawer from './components/Drawer.vue';
import { usePermission } from '/@/hooks/web/usePermission';
import { columns, searchFormSchema } from './components/tableData';

export default defineComponent({
  name: 'MenuManagement',
  components: { BasicTable, Drawer, TableAction },
  props: {},
  setup() {
    const { hasPermission } = usePermission();
    const tableRef = ref<Nullable<TableActionType>>(null);
    const getTableAction = () => {
      const tableAction = unref(tableRef);
      if (!tableAction) {
        throw new Error('tableAction is null');
      }
      return tableAction;
    };

    const [registerDrawer, { openDrawer, closeDrawer }] = useDrawer();
    const [registerTable, { reload, getSelectRows, setSelectedRowKeys }] = useTable({
      title: '角色列表',
      api: roleList,
      columns,
      formConfig: {
        labelWidth: 100,
        schemas: searchFormSchema,
      },
      useSearchForm: true,
      showTableSetting: true,
      beforeFetch: (res) => {
        if (res.createTime && res.createTime.length) {
          res.startTime = res.createTime[0];
          res.endTime = res.createTime[1];
          delete res.createTime;
        }
      },
      actionColumn: {
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right',
        width: 220,
      },
    });
    const getSelectRowList = () => {
      return getTableAction().getSelectRows();
    };
    const setSelectedRowKeyList = (arr) => {
      setSelectedRowKeys(arr);
    };
    const data: any = reactive({
      type: 'add',
    });
    //获取权限信息
    //数据权限
    const handleDataSuccess = async (formData) => {
      let params = { ...formData };
      delete params.code;
      delete params.name;
      try {
        await roleDataAssign(params);
        message.success('操作成功！');
        closeDrawer();
        reload();
      } catch (error) {}
    };
    //菜单权限
    const handlePowerSuccess = async (formData) => {
      console.log('我是权限', formData);

      let params = { ...formData };
      try {
        await assignRole(params);
        message.success('操作成功！');
        closeDrawer();
        reload();
      } catch (error) {}
    };
    //编辑
    const handleEditSuccess = async (formData) => {
      let params = { ...formData };
      try {
        await editRole(params);
        message.success('操作成功！');
        closeDrawer();
        reload();
      } catch (error) {}
    };
    //新增
    const handleAddSuccess = async (formData) => {
      let params = { ...formData };
      try {
        await addRole(params);
        message.success('操作成功！');
        closeDrawer();
        reload();
      } catch (error) {}
    };
    function handleCreate() {
      openDrawer(true, {
        isUpdate: false,
      });
      data.type = 'add';
    }

    function handleEdit(record: Recordable) {
      openDrawer(true, {
        record,
        isUpdate: true,
      });
      data.type = 'edit';
    }
    function handlePower(record: Recordable) {
      openDrawer(true, {
        record,
        isUpdate: true,
      });
      data.type = 'power';
    }
    function handleDataPermissions(record: Recordable) {
      openDrawer(true, {
        record,
        isUpdate: true,
      });
      data.type = 'dataPower';
    }

    //删除
    const handleDelete = async (record: Recordable) => {
      try {
        await deleteRole({ id: record.id });
        message.success('删除成功！');
        reload();
      } catch (error) {}
    };

    function handleSuccess(formData) {
      switch (data.type) {
        case 'add':
          handleAddSuccess(formData);
          break;
        case 'edit':
          handleEditSuccess(formData);
          break;
        case 'power':
          handlePowerSuccess(formData);
          break;
        case 'dataPower':
          handleDataSuccess(formData);
          break;
      }
    }

    function onFetchSuccess() {}

    return {
      ...toRefs(data),
      tableRef,
      registerTable,
      registerDrawer,
      handleCreate,
      handleEdit,
      handlePower,
      handleDelete,
      handleSuccess,
      onFetchSuccess,
      getSelectRowList,
      setSelectedRowKeyList,
      handleDataPermissions,
      hasPermission,
    };
  },
});
</script>
